use super::models::*;
use actix_web::{web, HttpResponse};

use uuid::Uuid;
use std::io::Write;
use std::io::Read;

fn write(content: &str) -> std::string::String {
    let name = Uuid::new_v4().hyphenated().to_string();
    let mut file = std::fs::File::create(&name).expect("create failed");
    file.write_all(content.as_bytes()).expect("write failed");
    name
}

fn run(data: web::Json<Runner>) -> std::string::String {
    let name = write(&data.code);

    use std::io::Write;
    use std::process::{Command, Stdio};

    let mut child = Command::new("python")
        .args([&name])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to spawn child process");

    let mut stdin = child.stdin.take().expect("Failed to open stdin");
    std::thread::spawn(move || {
        stdin.write_all(data.input.as_bytes()).expect("Failed to write to stdin");
    });

    let mut contents = String::new();
    let mut err = String::new();
    child.stdout.unwrap().read_to_string(&mut contents).unwrap();
    child.stderr.unwrap().read_to_string(&mut err).unwrap();
    std::fs::remove_file(&name).expect("Failed to remove file");
    contents + &err
}

pub async fn new_course(
    new_course: web::Json<Runner>,
) -> HttpResponse {
    println!("Received new Runner");
    // let code = new_course.code.clone();
    // let input = new_course.input.clone();

    // println!("{}", code);


    // let s = format!("{},  {}", code, input);  //返回值
    let s = run(new_course);

    let obj = ResponseObj {
        out: s.to_string(),
    };
    HttpResponse::Ok().json(obj)
}